package com.hopital5.zhangyz.service;

import com.hopital5.zhangyz.model.People;
import com.hopital5.zhangyz.repository.LabelRepository;
import com.hopital5.zhangyz.repository.PeopleRepository;
import com.hopital5.zhangyz.vo.request.PeopleVoRequest;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class PeopleService {
    @Autowired
    PeopleRepository peopleRepository;
    @Autowired
    LabelRepository labelRepository;

    public People save(PeopleVoRequest peopleVoRequest) {
        People people = People.builder()
                .name(peopleVoRequest.getName())
                .peopleSex(peopleVoRequest.getPeopleSex())
                .number(peopleVoRequest.getNumber())
                .labels(Optional.ofNullable(peopleVoRequest.getLabelIds())
                        .filter(CollectionUtils::isNotEmpty)
                        .map(labelIds -> labelRepository.findAll(labelIds))
                        .orElse(null)).build();
        return peopleRepository.save(people);
    }

    @Transactional
    public People update(PeopleVoRequest peopleVoRequest) {
        People people = peopleRepository.findOne(peopleVoRequest.getPeopleId());
        people.setName(peopleVoRequest.getName());
        people.setPeopleSex(peopleVoRequest.getPeopleSex());
        people.setNumber(peopleVoRequest.getNumber());
        people.getLabels().clear();
        Optional.ofNullable(peopleVoRequest.getLabelIds())
                .filter(CollectionUtils::isNotEmpty)
                .map(labelIds -> labelRepository.findAll(labelIds))
                .ifPresent(labels -> labels.forEach(people::addLabel));
        return people;
    }

    public People findOne(Long id) {
        return peopleRepository.findOne(id);
    }

    public void delete(Long id) {
        peopleRepository.delete(id);
    }

    public void delete(People people) {
        peopleRepository.delete(people);
    }
}

